package com.yunhe.option.service.base.impl;

import com.yunhe.option.domain.base.TimeScale;
import com.yunhe.common.exception.ArgumentErrorException;
import com.yunhe.common.exception.ObjectNotFoundException;
import com.yunhe.common.exception.UniqueConstraintsException;
import com.yunhe.option.repository.base.TimeScaleRepository;
import com.yunhe.option.service.base.TimeScaleService;
import com.yunhe.common.util.QueryUtil;
import com.yunhe.common.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

/**
 * 时间尺度Service
 * @desc 时间尺度服务类实现
 * @author liuronglei
 */
@Service
public class TimeScaleServiceImpl implements TimeScaleService {
    @Autowired
    private TimeScaleRepository timeScaleRepository;

    /**
     * 时间尺度对象处理和判断
     * @param timeScale 时间尺度对象
     */
    private void processBeforeSave(TimeScale timeScale)
            throws ArgumentErrorException, UniqueConstraintsException {
        //判断时间尺度代码、编号、标题是否为空
        if (timeScale.getCode() == null
                || StringUtil.isEmpty(timeScale.getName())
                || StringUtil.isEmpty(timeScale.getTitle())) {
            throw new ArgumentErrorException("时间尺度代码、编号、标题不能为空");
        }
        //判断代码是否已存在
        TimeScale typeByCode = this.findByCode(timeScale.getCode());
        if (typeByCode != null) {
            if (timeScale.getId() == null || typeByCode.getId().longValue() != timeScale.getId().longValue()) {
                throw new UniqueConstraintsException("该时间尺度代码已存在");
            }
        }
        //判断编号是否已存在
        TimeScale typeByName = this.findByName(timeScale.getName());
        if (typeByName != null) {
            if (timeScale.getId() == null || typeByName.getId().longValue() != timeScale.getId().longValue()) {
                throw new UniqueConstraintsException("该时间尺度编号已存在");
            }
        }
        //如果序号为空，则默认为代码
        if (timeScale.getSn() == null && timeScale.getCode() != null) {
            timeScale.setSn(timeScale.getCode());
        }
    }

    /**
     * 新增时间尺度
     * @param timeScale 时间尺度对象
     */
    @Override
    @Transactional
    public TimeScale createTimeScale(TimeScale timeScale)
            throws ArgumentErrorException, UniqueConstraintsException {
        timeScale.setId(null);
        processBeforeSave(timeScale);
        return timeScaleRepository.save(timeScale);
    }

    /**
     * 删除时间尺度
     * @param timeScaleId 时间尺度ID
     */
    @Override
    @Transactional
    public void deleteTimeScale(Long timeScaleId) {
        timeScaleRepository.deleteById(timeScaleId);
    }

    /**
     * 更新时间尺度（更新全部字段）
     * @param timeScale 时间尺度对象
     */
    @Override
    @Transactional
    public TimeScale updateTimeScale(TimeScale timeScale)
            throws ArgumentErrorException, UniqueConstraintsException, ObjectNotFoundException {
        boolean exists = timeScale.getId() != null && timeScaleRepository.existsById(timeScale.getId());
        if (!exists) {
            throw new ObjectNotFoundException("找不到ID为" + timeScale.getId() + "的时间尺度");
        }
        processBeforeSave(timeScale);
        return timeScaleRepository.save(timeScale);
    }

    /**
     * 更新时间尺度（更新指定字段）
     * @param timeScaleId 时间尺度ID
     * @param code 代码
     * @param name 编号
     * @param title 标题
     * @param sn 排序序号
     * @param activity 是否可用
     */
    @Override
    @Transactional
    public TimeScale updateTimeScale(Long timeScaleId,
                                     Long code,
                                     String name,
                                     String title,
                                     Long sn,
                                     Boolean activity)
            throws ArgumentErrorException, ObjectNotFoundException, UniqueConstraintsException {
        TimeScale timeScale = this.findByTimeScaleId(timeScaleId);
        if (timeScale == null) {
            throw new ObjectNotFoundException("找不到ID为" + timeScaleId + "的时间尺度");
        }
        Optional.ofNullable(code).ifPresent(timeScale::setCode);
        Optional.ofNullable(name).ifPresent(timeScale::setName);
        Optional.ofNullable(title).ifPresent(timeScale::setTitle);
        Optional.ofNullable(sn).ifPresent(timeScale::setSn);
        Optional.ofNullable(activity).ifPresent(timeScale::setActivity);
        processBeforeSave(timeScale);
        return timeScaleRepository.save(timeScale);
    }

    /**
     * 根据ID获得时间尺度对象
     * @param id 状态ID
     */
    @Override
    public TimeScale findByTimeScaleId(Long id) {
        return timeScaleRepository.findById(id).orElse(null);
    }

    /**
     * 根据代码获得时间尺度对象
     * @param code 代码
     */
    @Override
    public TimeScale findByCode(Long code) {
        return timeScaleRepository.findByCode(code);
    }

    /**
     * 根据编号获得时间尺度对象
     * @param name 编号
     */
    @Override
    public TimeScale findByName(String name) {
        return timeScaleRepository.findByName(name);
    }

    /**
     * 获得全部时间尺度对象
     */
    @Override
    public Iterable<TimeScale> findTimeScales() {
        return timeScaleRepository.findAll(QueryUtil.defaultSort());
    }

}
